package me.firstapp.repository.weixin.system.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.system.Broadcast;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.weixin.system.BroadcastRepository;

@Repository
public class BroadcastRepositoryImpl extends EntityRepositoryImpl<Broadcast> implements BroadcastRepository {

	@Override
	protected Class<Broadcast> getPersistentClass() {
		return Broadcast.class;
	}

	@Override
	public Page<Broadcast> findBroadcastPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType) {
		StringBuilder sql = new StringBuilder(" FROM Broadcast bean where 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		if (searchParams != null) {
			Set<String> keys = searchParams.keySet();
			for (String key : keys) {
				Object value = searchParams.get(key);
				if (value != null) {
					sql.append(" AND bean." + key + " LIKE :" + key + " ");
					parameters.put(key, "%" + value + "%");
				}
			}
		}

		if (StrUtils.isNotNULL(sortParam) && StrUtils.isNotNULL(sortType)) {
			sql.append(" ORDER BY " + sortParam + " " + sortType);
		}

		return super.queryForPage(Broadcast.class, sql.toString(), parameters, pageNo, pageSize);
	}

	@Override
	public List<Broadcast> findBroadcasts() {
		StringBuilder sql = new StringBuilder(" FROM Broadcast bean where 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" AND bean.status = :status ");
		parameters.put("status", Broadcast.STATUS_ON);

		sql.append(" ORDER BY bean.sort ASC ");

		return super.query(Broadcast.class, sql.toString(), parameters);
	}

}
